package com.run.gulimall.order.service.impl;

import com.rabbitmq.client.Channel;
import com.run.gulimall.order.entity.OrderEntity;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.run.common.utils.PageUtils;
import com.run.common.utils.Query;

import com.run.gulimall.order.dao.OrderItemDao;
import com.run.gulimall.order.entity.OrderItemEntity;
import com.run.gulimall.order.service.OrderItemService;

@RabbitListener(queues = {"direct-java-queue"})
@Service("orderItemService")
public class OrderItemServiceImpl extends ServiceImpl<OrderItemDao, OrderItemEntity> implements OrderItemService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderItemEntity> page = this.page(
                new Query<OrderItemEntity>().getPage(params),
                new QueryWrapper<OrderItemEntity>()
        );

        return new PageUtils(page);
    }
    /**
     *  使用该监听注解前须确保已开启RabbitMQ注解
     *  1.Message message: 原生消息类型 详细信息
     * 	2.T<发送消息的类型> OrderEntity orderEntity  [Spring自动帮我们转换]
     * 	3.Channel channel: 当前传输数据的通道
     *
     * 	// 同一个消息只能被一个人收到
     *
     *
     * 	@RabbitListener： 只能标注在类、方法上 配合 @RabbitHandler
     * 	@RabbitHandler: 只能标注在方法上	[重载区分不同的消息]
     */
//    @RabbitListener(queues = {"direct-java-queue"})
    @RabbitHandler
    public void receiveMessageA(Message message, OrderEntity orderEntity, Channel channel){
        System.out.println("消息 "+orderEntity.getReceiverName() + " 被消费");
        //channel通道中按顺序自增的消息属性。每接收一条＋1
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        //签收消息
        try {
            //消息号，是否批量处理
            channel.basicAck(deliveryTag,false);
            //退货
            //long deliveryTag, boolean multiple, boolean requeue(是否重新入队)
//            channel.basicNack(deliveryTag,false,false);
            //long deliveryTag, boolean requeue
//            channel.basicReject();
        } catch (IOException e) {
            //网络中断

        }
    }

    @RabbitHandler
    public void receiveMessageB(Message message, OrderItemEntity orderEntity, Channel channel){
        System.out.println("消息 "+orderEntity.getOrderSn() + " 被消费");
    }
}